<?php

namespace lib\Server\Heartbeat;

use lib\Root;

class Base
{
	static $register_tcp    = null;
	static $sendErrorNum    = 0;
	static $broadcastIng    = false;
	static $broadcastUDP    = null;
	static $connectErrorNum = 0;

	function __construct($server, $config)
	{
		echo PHP_EOL . '开始连接服务中心{' . $config['register_host'] . ':' . $config['register_port'] . ',timeout:' . (float)$config['register_time_out'] . '}' . PHP_EOL;

		if (null === self::$register_tcp) {
			#心跳包 tcp 协议
			$this->connect($config);
		}

		if (null === self::$broadcastUDP) {
			#无法连接服务中心时 UDP 协议进行 指定ip段广播
			self::$broadcastUDP = new \swoole_client(SWOOLE_SOCK_UDP);
		}

		$this->send($server, $config);
	}

	public function connect($config)
	{
		//create tcp client
		self::$register_tcp = new \swoole_client(SWOOLE_SOCK_TCP);
		//connect register service
		if (!self::$register_tcp->connect($config['register_host'], (int)$config['register_port'], (float)$config['register_time_out'])) {
			//connect error
			self::$connectErrorNum++;
			self::$register_tcp->close();
//			echo("无法连接到服务中心: {$config['register_host']}:{$config['register_port']}" . self::$register_tcp->errCode . PHP_EOL);
		}
		else {
			//connect success
			//set config
			self::$register_tcp->set(array(
				'socket_buffer_size' => 1024 * 1024 * 2, //2M缓存区
			));

			self::$broadcastIng    = false;
			self::$connectErrorNum = 0;
			self::$sendErrorNum    = 0;
//			echo '连接成功' . PHP_EOL;
		}
	}

	public function send($server, $config)
	{
//		echo '开始发送数据' . PHP_EOL;
		swoole_timer_tick(1000, function () use ($server, $config) {
			if (!self::$broadcastIng && self::$connectErrorNum > 10) {
				self::$broadcastIng = true;
				$this->broadcast();
			}

			if (!self::$register_tcp->isConnected() || self::$sendErrorNum > 3) {
//				echo '开始重新连接连接服务中心' . PHP_EOL;
				$this->connect($config);
			}
			else {
				$stats = $server->stats();
				$data  = $this->sendData($server, $config);
				if (!self::$register_tcp->send($data)) {
					self::$sendErrorNum++;
				}

				if (!$recvData = self::$register_tcp->recv()) {
					self::$sendErrorNum++;
				}
				else {
					$this->getData($recvData);
				}
			}
		});
	}

	public function broadcast()
	{
		swoole_timer_tick(1000, function () {
			if (self::$broadcastIng) {
				//获取当先模式广播数据
				$sendData = $this->broadcastData();
				//获取广播ip段
				var_dump(Root::Config('broadcast'));
			}
		});
	}
}